package bch.maven.plugin.config;

import com.google.auto.service.AutoService;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.tools.Diagnostic;
import java.util.*;

@SupportedAnnotationTypes("bch.maven.plugin.config.GenerateExtraField")
@SupportedSourceVersion(SourceVersion.RELEASE_21)
@AutoService(Processor.class)
public class ExtraFieldProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        processingEnv.getMessager().printMessage(
                Diagnostic.Kind.NOTE,
                "Processing extra fields..."
        );

        // 遍历所有被注解标记的字段
        Map<TypeElement, Set<Integer>> classOrderMap = new HashMap<>();

        for (Element element : roundEnv.getElementsAnnotatedWith(GenerateExtraField.class)) {
            if (element.getKind() != ElementKind.FIELD)  {
                continue;
            }

            VariableElement field = (VariableElement) element;
            TypeElement clazz = (TypeElement) field.getEnclosingElement();
            GenerateExtraField annotation = field.getAnnotation(GenerateExtraField.class);

            classOrderMap.putIfAbsent(clazz, new HashSet<>());
            Set<Integer> orders = classOrderMap.get(clazz);

            if (orders.contains(annotation.order())) {
                // 报错：同一个类中 order 重复
                processingEnv.getMessager().printMessage(
                        Diagnostic.Kind.ERROR,
                        "Duplicate order " + annotation.order() + " in class " + clazz.getSimpleName(),
                        field
                );
            } else {
                orders.add(annotation.order());
            }
        }

        return true;
    }
}
